<template>
	<view>
		<u-navbar title="提现" @rightClick="rightClick" :placeholder="true" :autoBack="true"></u-navbar>
		<view class="page">
			<view class="tabs">
				<view class="item" :class="{'active' : 0 == currentIndex }" @click="checkTabs(0)">
					微信充值余额
				</view>
				<view class="item" :class="{'active' : 1 == currentIndex }" @click="checkTabs(1)">
					公对公余额
				</view>
			</view>
			<view class="top">
				<view class="weixin" v-if="currentIndex == 0">
					<text class="label">微信充值可提现余额（元）：</text>
					<text
						class="money">{{utils.rmoney(computedBalance(Info.aucdeposit.depositBalance,Info.aucdeposit.frozenAmount))}}</text>
				</view>
				<view class="ptp" v-if="currentIndex == 1">
					<text class="label">公对公可提现余额（元）：</text>
					<text
						class="money">{{utils.rmoney(computedBalance(Info.aucdeposit.companyRechargeBalance,Info.aucdeposit.companyRechargeFrozenAmount))}}</text>
				</view>
				<view class="inputMoney">
					<view class="text">
						输入提现金额
					</view>
					<view class="inputView">
						<input type="digit" @blur="inputBlur" v-model="price" style="font-size: 60rpx;width: 90%;"
							placeholder="0.00" class="amount-input" />
					</view>
				</view>
			</view>
			<view v-if="!realAuthInfo || [3,4].includes(realAuthInfo.status)">
				<view class="shimingTips">
					<view>您当前还未实名认证，请先实名认证</view>
					<view class="shimingTips-right">
						<view @click="toAuth">
							前往认证 >
						</view>
					</view>
				</view>
			</view>
			<view class="type" v-if="(0 == currentIndex && weixin) || (1 == currentIndex && ptp)">
				<view class="text">
					选择提现方式
				</view>
				<view>
					<!-- 公对公 -->
					<view>
						<view class="type-line" data-index="1">
							<view class="type-line-left">
								<view>
									<image src="/static/reCharge/ptp.png" style="width: 50rpx;height: 50rpx;" mode=""></image>
								</view>
								<view class="line-text">
									公对公
								</view>
							</view>
							<view>
								<image src="/static/reCharge/check.png" style="width: 40rpx;height: 40rpx;" mode="">
								</image>
							</view>
						</view>
						<view class="checkAccount" @click="toAccountMan" v-if="realAuthInfo">
							选择账号>
						</view>
						<view class="form">
							<u--form labelPosition="left" labelWidth="auto" :model="form" :rules="rules" ref="uForm">
								<u-form-item label="开户名称：" prop="accountName" required>
									<u--textarea v-model="form.accountName" style="border: none;" disabled placeholder="请输入开户名称"
										autoHeight></u--textarea>
								</u-form-item>
								<view style="font-size: 14px;color: red;margin-left: 10rpx;margin-top: 10rpx;">
									<text>开户名称需与认证名称一致，若账号名称不符请重新编辑账号！</text>
								</view>
								<u-form-item label="银行卡号：" prop="bankCardNo" required>
									<u--textarea v-model="form.bankCardNo" style="border: none;" disabled placeholder="请输入账号"
										autoHeight></u--textarea>
								</u-form-item>
								<u-form-item label="银行名称：" prop="bankName" required>
									<u--textarea v-model="form.bankName" style="border: none;" disabled placeholder="请输入银行名称，如：招商银行"
										autoHeight></u--textarea>
								</u-form-item>
								<u-form-item label="开 户 行：" prop="bankBranch" required>
									<u--input v-model="form.bankBranch" border="none" disabled
										placeholder="请输入开户行名称，如：芜湖分行营业部"></u--input>
								</u-form-item>
								<u-form-item label="联系人姓名：" prop="contactName" required>
									<u--input v-model="form.contactName" border="none" placeholder="请输入联系人姓名"></u--input>
								</u-form-item>
								<u-form-item label="联系人手机号：" prop="contactPhone" required>
									<u--input v-model="form.contactPhone" border="none" placeholder="请输入联系人手机号"></u--input>
								</u-form-item>
							</u--form>
						</view>
						<u-form-item label="备注：" prop="" labelWidth="60">
							<u--textarea placeholder="请输入" style="background-color: #F6F6F6;border: none;" v-model="remark"
								maxlength="200"></u--textarea>
						</u-form-item>
					</view>
				</view>
			</view>
			<view class="btn">
				<view class="tip" v-if="(0 == currentIndex && weixin) || (1 == currentIndex && ptp)">
					<image src="/static/reCharge/uncheck.png" style="width: 40rpx;height: 40rpx;" v-if="!ischecked"
						@click="ischecked = !ischecked" mode="">
					</image>
					<image src="/static/reCharge/check.png" style="width: 40rpx;height: 40rpx;" v-if="ischecked"
						@click="ischecked = !ischecked" mode="">
					</image>
					<view style="margin-left: 20rpx;">请阅读并同意 <text style="color: blue;" @click="toXieYi">《提现协议》</text> </view>
				</view>
				<u-button color="#28AC3E" text="提现" @click="toWithdrawal"></u-button>
			</view>
			<view class="tips">
				<text v-html="content"></text>
			</view>
		</view>
		<u-keyboard ref="uKeyboard" mode="number" :showCancel="false" :showConfirm="false" @change="keyboardChange"
			@backspace="backspace" :overlay="false" :show="show"></u-keyboard>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				show: false,
				price: '',
				type: 0,
				form: {
					accountName: '',
					bankCardNo: '',
					bankName: '',
					bankBranch: '',
					contactName: '',
					contactPhone: '',
				},
				currentIndex: 0,
				ischecked: false,
				tabList: [{
						name: "微信充值余额"
					},
					{
						name: "公对公余额"
					},
				],
				Info: this.$store.state.Info,
				rules: {
					accountName: [{
						required: true,
						message: '请填写开户名称',
						trigger: ['blur', 'change']
					}],
					bankCardNo: [{
						required: true,
						message: '请填写银行卡号',
						trigger: ['blur', 'change']
					}],
					bankName: [{
						required: true,
						message: '请填写开户名行',
						trigger: ['blur', 'change']
					}],
					bankBranch: [{
						required: true,
						message: '请填写开户支行',
						trigger: ['blur', 'change']
					}],
					contactName: [{
						required: true,
						message: '请填写联系人姓名',
						trigger: ['blur', 'change']
					}],
					contactPhone: [{
							required: true,
							message: '请填写联系人手机号',
							trigger: ['blur', 'change']
						},
						{
							// 自定义验证函数，见上说明
							validator: (rule, value, callback) => {
								// 上面有说，返回true表示校验通过，返回false表示不通过
								// 就是返回true或者false的

								return uni.$u.test.mobile(value);
							},
							message: '手机号格式不正确',
							// 触发器可以同时用blur和change
							trigger: ['change', 'blur'],
						}
					],
				},
				fileList1: [],
				content: null,
				Info: this.$store.state.Info,
				urlParams: this.$store.state.urlParams,
				remark: '',
				isDisabledAccountName: false,
				withdrawalType: {},
				weixin: "",
				ptp: "",
				realAuthInfo: null,
				JTH5_withdraw_maxAmount: 0,
				JTH5_withdraw_maxNum: 0,
				JTH5_code_switch: false,
				withdrawalCount: 0, //当日提现次数
			}
		},
		onReady() {
			//如果需要兼容微信小程序，并且校验规则中含有方法等，只能通过setRules方法设置规则。
			// this.$refs.uForm.setRules(this.rules)
		},
		async onLoad() {
			this.weixin = await this.getDictOne("JTH5_withdrawal_wx") == 1;
			this.ptp = await this.getDictOne("JTH5_withdrawal_ptp") == 1;
			this.JTH5_withdraw_maxAmount = await this.getDictOne("JTH5_withdraw_maxAmount");
			this.JTH5_withdraw_maxNum = await this.getDictOne("withdrawMaxNum");
			this.JTH5_code_switch = await this.getDictOne("JTH5_code_switch") == 1;
			this.withdrawalCount = await this.getWithdrawalCount();
			await this.getAgreement();
			await this.getCallinfoInfo();
			this.realAuthInfo = await this.realAuthDetail();
			uni.$on("accountItem", (data) => {
				console.log(data);
				this.form.accountName = data.accountName;
				this.form.bankCardNo = data.bankCardNo;
				this.form.bankName = data.bankName;
				this.form.bankBranch = data.bankBranch;
				this.form.contactName = data.contactName;
				this.form.contactPhone = data.contactPhone;
			})
		},
		onUnload() {
			uni.$off("accountItem")
		},
		onShow() {
			this.getCallinfoInfo();
		},
		methods: {
			async getWithdrawalCount() {
				let result = await this.api.withdrawalCount();
				return result.data.data
			},
			computedBalance(a, b) {
				return (Number(a) * 100 - Number(b) * 100) / 100
			},
			//查询实名信息
			async realAuthDetail() {
				let result = await this.api.realAuthDetail();
				return result.data.data;
			},
			toAccountMan() {
				uni.navigateTo({
					url: "/pages/accountMan/index"
				})
			},
			toXieYi() {
				uni.navigateTo({
					url: "/pages/precautions/index?code=gdgtxxy"
				})
			},
			//跳转认证页面
			toAuth() {
				if (this.JTH5_code_switch) {
					uni.navigateTo({
						url: "/pages/authentication/index"
					})
				} else {
					uni.navigateTo({
						url: "/pages/realNameAuth/index"
					})
				}
			},
			//获取协议
			getAgreement() {
				this.api.getAgreement("txsm").then(res => {
					console.log(res);
					this.content = res.data.data.content;
				})
			},
			async getDictOne(code) {
				let res = await this.api.getDictOne(code);
				return res.data.data.dictValue;
			},
			checkTabs(index) {
				this.currentIndex = index;
			},
			/**
			 * 查询账户信息
			 */
			getCallinfoInfo() {
				let params = {
					...uni.getStorageSync("urlParams")
				}
				this.api.getCallinfoInfo(params).then(
					res => {
						if (!res.data.data.erpCode) {
							uni.showModal({
								title: '提示',
								content: '未查询到相关信息！！',
								showCancel: false,
								success: function(res) {
									if (res.confirm) {
										console.log('用户点击确定');
										webUni.postMessage({
											data: {
												type: "back",
												data: []
											},
										})
									}
								}
							});
						}
						this.Info = res.data.data;
						uni.setStorageSync("Info", res.data.data);
						uni.setStorageSync("wxUserInfo", {
							openId: res.data.data.openId,
							unionId: res.data.data.unionId,
							wxNickName: res.data.data.wxNickName,
						});
					})
			},
			//正则匹配金额
			inputBlur(e) {
				if (!e.target.value) {
					return
				}
				// 正则表达式
				const regex = /^\d+(\.\d{0,2})?$/;

				if (!regex.test(e.target.value)) {
					uni.$u.toast("请输入正确金额")
				}
			},
			getAccountName() {
				this.api.getaccountname({
					...uni.getStorageSync("urlParams")
				}).then(res => {
					console.log(res.data.data);
					this.form.accountName = res.data.data;
				})
			},
			/**
			 * 查询账号信息
			 */
			getAccountInfo() {
				this.api.getAccountInfo({
					...uni.getStorageSync("urlParams")
				}).then(res => {
					console.log(1, res.data);
					if (res.data.data) {
						if (res.data.data.bankName || res.data.data.bankCardNo || res.data.data.bankBranch) {
							this.isDisabled = true;
							this.form.bankName = res.data.data.bankName;
							this.form.bankCardNo = res.data.data.bankCardNo;
							this.form.bankBranch = res.data.data.bankBranch;
							this.form.accountName = res.data.data.accountName;
						}
					}
				})
			},
			check(type) {
				this.type = type;
			},
			toPay(type) {
				uni.navigateTo({
					url: "/pages/authentication/index?type=" + type
					// url: "/pages/authPage/index?type=" + type
				})
			},
			rightClick() {

			},
			// 删除图片
			deletePic(event) {
				this[`fileList${event.name}`].splice(event.index, 1);
				this.form.proofPayment = ""
			},
			// 新增图片
			async afterRead(event) {
				// 当设置 multiple 为 true 时, file 为数组格式，否则为对象格式
				let lists = [].concat(event.file);
				let fileListLen = this[`fileList${event.name}`].length;
				lists.map((item) => {
					this[`fileList${event.name}`].push({
						...item,
						status: "uploading",
						message: "上传中",
					});
				});
				for (let i = 0; i < lists.length; i++) {
					const result = await this.uploadFile(lists[i].url);
					let item = this[`fileList${event.name}`][fileListLen];
					this[`fileList${event.name}`].splice(
						fileListLen,
						1,
						Object.assign(item, {
							status: "success",
							message: "",
							url: result,
						})
					);
					fileListLen++;
				}
				this.form.proofPayment = this.fileList1[0].url
			},
			//立即支付
			async toWithdrawal() {
				if ((0 == this.currentIndex && !this.weixin) || (1 == this.currentIndex && !this.ptp)) {
					return
				}
				this.realAuthInfo = await this.realAuthDetail();
				if (!this.realAuthInfo || [3, 4].includes(this.realAuthInfo.status)) {
					uni.$u.toast("提现需完成实名认证，请您先实名认证！");
					return;
				}
				let that = this;
				if (this.price == '') {
					uni.$u.toast('请输入提现金额');
					return
				}
				const moneyRegex = /^\d+(\.\d{0,2})?$/;
				if (!moneyRegex.test(this.price)) {
					uni.$u.toast("请输入正确金额");
					return
				}
				if(this.realAuthInfo.name != this.form.accountName){
					return uni.$u.toast("开户名称与认证名称不符，重新编辑账号！");
				}
				if (this.currentIndex == 0) {
					if (Number(this.price) > this.computedBalance(this.Info.aucdeposit.depositBalance, this.Info.aucdeposit
							.frozenAmount)) {
						uni.$u.toast("提现金额不能大于可提现余额");
						return
					}
				} else {
					if (Number(this.price) > this.computedBalance(this.Info.aucdeposit.companyRechargeBalance, this.Info
							.aucdeposit
							.companyRechargeFrozenAmount)) {
						uni.$u.toast("提现金额不能大于可提现余额");
						return
					}
				}
				if (Number(this.price) > Number(this.JTH5_withdraw_maxAmount)) {
					uni.$u.toast(`提现金额大于单笔限制最大提现金额${this.JTH5_withdraw_maxAmount}`);
					return
				}
				if (Number(this.withdrawalCount) >= Number(this.JTH5_withdraw_maxNum)) {
					uni.$u.toast('提现次数超出每日发起最大提现次数');
					return
				}
				this.$refs.uForm.validate().then((vaild) => {
					if (vaild) {
						that.api.withdrawal({
							...uni.getStorageSync("urlParams"),
							price: that.price,
							...that.form,
							remark: this.remark,
							balanceType: this.currentIndex == 0 ? 1 : 2,
							type: '03'
						}).then(res => {
							uni.$u.toast('操作成功');
							uni.redirectTo({
								url: `/pages/withdrawal/success?payType=03&price=${that.price}`
							})
						})
					}
				})
			}
		}
	}
</script>

<style scoped lang="scss">
	page {
		background-color: #F6F6F6;
	}

	.page {
		margin: 20rpx;
	}

	::v-deep .u-form-item__body {
		padding: 20rpx 25rpx;
		background-color: #F6F6F6;
		border-radius: 10rpx;
		margin: 10rpx 0rpx;

		.u-form-item__body__left__content__label {
			font-weight: 500;
		}
	}

	.checkAccount {
		display: flex;
		align-items: center;
		justify-content: end;
		color: #9295F7;
		font-size: 25rpx;
		font-weight: bold;
		margin: 10rpx 10rpx;
	}

	.top {
		padding: 20rpx;
		background-color: #FFFFFF;
	}

	.label {
		font-family: PingFang SC;
		font-weight: 500;
		font-size: 28rpx;
		color: #999999;
		line-height: 40rpx;
	}

	.shimingTips {
		background-color: #F8DD02;
		display: flex;
		align-items: center;
		justify-content: space-between;
		padding: 20rpx 10rpx;
		margin-top: 20rpx;
		font-size: 22rpx;
		font-weight: bold;

		.shimingTips-left {}

		&-right {
			display: flex;
			align-items: center;
			color: #15298C;
		}
	}

	.money {
		font-family: PingFang SC;
		font-weight: bold;
		font-size: 32rpx;
		color: #333333;
		line-height: 45rpx;
	}

	.weixin {}

	.ptp {
		// margin-top: 20rpx;
	}

	.inputMoney {
		margin-top: 40rpx;
		font-family: PingFang SC;
		font-weight: bold;
		font-size: 32rpx;
		color: #333333;
		line-height: 45rpx;

		.inputView {
			width: 100%;
			margin-top: 20rpx;
		}
	}

	.type {
		margin-top: 20rpx;
		padding: 20rpx;
		background-color: #FFFFFF;

		.text {
			font-family: PingFang SC;
			font-weight: bold;
			font-size: 32rpx;
			color: #333333;
			line-height: 45rpx;
		}
	}

	.type-line {
		display: flex;
		align-items: center;
		justify-content: space-between;
		margin-top: 30rpx;
		padding: 10rpx 20rpx;

		.type-line-left {
			display: flex;
		}

		.line-text {
			margin-left: 20rpx;
			font-family: PingFang SC;
			font-weight: 500;
			font-size: 30rpx;
			color: #333333;
			line-height: 42rpx;
		}
	}

	.remark {
		display: flex;
		margin-top: 30rpx;
		font-family: PingFang SC;
		font-weight: bold;
		font-size: 28rpx;
		color: #333333;
		line-height: 40rpx;
	}

	.form {
		// margin: 20rpx 10rpx;
	}

	.btn {
		margin: 50rpx 40rpx;
	}

	.tip {
		font-family: PingFang SC;
		font-weight: bold;
		font-size: 24rpx;
		line-height: 33rpx;
		display: flex;
		align-items: center;
		margin-bottom: 30rpx;
	}

	.tips {
		margin: 30rpx 20rpx;
		padding: 10rpx;
		font-family: PingFang SC;
		font-weight: 500;
		font-size: 24rpx;
		color: #666666;
		line-height: 36rpx;
	}

	.user {
		display: flex;
		align-items: center;
		justify-content: space-between;
		margin-left: 80rpx;
		margin-top: 20rpx;

		.user-left {
			display: flex;
			align-items: center;
			justify-content: space-between;
		}

		.username {
			margin-left: 20rpx;
		}
	}

	.bindWeixin {
		display: flex;
		align-items: center;
		justify-content: space-between;
	}

	.tabs {
		display: flex;
		align-items: center;
		justify-content: space-around;

		.item {
			font-weight: bold;
			font-size: 25rpx;
			margin: 10rpx 0rpx 25rpx 0rpx;
			padding: 10rpx;
		}

		.active {
			border-bottom: 1px solid;
			color: #1684FC;
		}
	}
</style>